/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * LoginFrame.java
 *
 * Created on 15-Apr-2009, 1:31:04 PM
 */

package jogs.client;

import java.io.*;
import java.net.*;

/**
 *
 * @author lanctot
 */
public class LoginFrame extends javax.swing.JFrame {

    public static String metaServerHost = "localhost";
    public static int metaServerPort = 22311;

    public static String arg_username = "";
    public static String arg_password = "";

    Main main;

    /** Creates new form NumberAdditionUI */
    public LoginFrame() {
        initComponents();
    }

    public LoginFrame(Main _m, boolean nowindow) {
      main = _m;

      if (!nowindow)
        initComponents();
      
      if (!arg_username.equals("") && !arg_password.equals(""))
        login();
    }


    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
  // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
  private void initComponents() {

    jPanel1 = new javax.swing.JPanel();
    title = new javax.swing.JLabel();
    username = new javax.swing.JLabel();
    password = new javax.swing.JLabel();
    usernameField = new javax.swing.JTextField();
    passwordField = new javax.swing.JPasswordField();
    login = new javax.swing.JButton();
    statusmsg = new javax.swing.JLabel();

    setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

    jPanel1.setBackground(new java.awt.Color(253, 248, 219));

    title.setFont(new java.awt.Font("URW Bookman L", 0, 48));
    title.setText("The Gamer's Guild");

    username.setText("Username:");
    username.addKeyListener(new java.awt.event.KeyAdapter() {
      public void keyReleased(java.awt.event.KeyEvent evt) {
        usernameKeyReleased(evt);
      }
    });

    password.setText("Password:");

    usernameField.setRequestFocusEnabled(false);
    usernameField.addActionListener(new java.awt.event.ActionListener() {
      public void actionPerformed(java.awt.event.ActionEvent evt) {
        usernameFieldActionPerformed(evt);
      }
    });

    passwordField.addActionListener(new java.awt.event.ActionListener() {
      public void actionPerformed(java.awt.event.ActionEvent evt) {
        passwordFieldActionPerformed(evt);
      }
    });

    login.setText("Login");
    login.addActionListener(new java.awt.event.ActionListener() {
      public void actionPerformed(java.awt.event.ActionEvent evt) {
        loginActionPerformed(evt);
      }
    });

    statusmsg.setForeground(new java.awt.Color(0, 30, 255));

    org.jdesktop.layout.GroupLayout jPanel1Layout = new org.jdesktop.layout.GroupLayout(jPanel1);
    jPanel1.setLayout(jPanel1Layout);
    jPanel1Layout.setHorizontalGroup(
      jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
      .add(jPanel1Layout.createSequentialGroup()
        .add(jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
          .add(jPanel1Layout.createSequentialGroup()
            .add(148, 148, 148)
            .add(jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.TRAILING)
              .add(username)
              .add(password))
            .add(jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
              .add(jPanel1Layout.createSequentialGroup()
                .add(5, 5, 5)
                .add(login))
              .add(jPanel1Layout.createSequentialGroup()
                .add(6, 6, 6)
                .add(jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING, false)
                  .add(passwordField)
                  .add(usernameField, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 153, Short.MAX_VALUE)))))
          .add(jPanel1Layout.createSequentialGroup()
            .add(46, 46, 46)
            .add(title)))
        .addContainerGap(55, Short.MAX_VALUE))
      .add(org.jdesktop.layout.GroupLayout.TRAILING, jPanel1Layout.createSequentialGroup()
        .addContainerGap(171, Short.MAX_VALUE)
        .add(statusmsg, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 260, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
        .add(112, 112, 112))
    );
    jPanel1Layout.setVerticalGroup(
      jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
      .add(jPanel1Layout.createSequentialGroup()
        .add(35, 35, 35)
        .add(title)
        .addPreferredGap(org.jdesktop.layout.LayoutStyle.UNRELATED)
        .add(statusmsg, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 21, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
        .add(31, 31, 31)
        .add(jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
          .add(usernameField, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 18, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
          .add(username))
        .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
        .add(jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
          .add(password)
          .add(passwordField, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 18, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
        .add(28, 28, 28)
        .add(login)
        .addContainerGap(53, Short.MAX_VALUE))
    );

    org.jdesktop.layout.GroupLayout layout = new org.jdesktop.layout.GroupLayout(getContentPane());
    getContentPane().setLayout(layout);
    layout.setHorizontalGroup(
      layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
      .add(jPanel1, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
    );
    layout.setVerticalGroup(
      layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
      .add(jPanel1, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
    );

    pack();
  }// </editor-fold>//GEN-END:initComponents

    private void usernameFieldActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_usernameFieldActionPerformed
        // TODO add your handling code here:
        //System.out.println("Username action performed.");
        login();
}//GEN-LAST:event_usernameFieldActionPerformed

    private void loginActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_loginActionPerformed
        // TODO add your handling code here:
        //System.out.println("login action performed.");
        login();
}//GEN-LAST:event_loginActionPerformed

    private void passwordFieldActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_passwordFieldActionPerformed
        // TODO add your handling code here:
        //System.out.println("password action performed.");
        login();
    }//GEN-LAST:event_passwordFieldActionPerformed

    private void usernameKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_usernameKeyReleased
      // TODO add your handling code here:
    }//GEN-LAST:event_usernameKeyReleased

    private void error(String s)
    {
      System.out.println(s);
      System.exit(-1);
    }

    private void assert_receive(String line, String expect)
    {
      if (!line.equals(expect))
        error("Expected: " + expect + ", got: " + line);
    }

    private synchronized void login()
    {
      boolean nowindow = (!arg_username.equals("") && !arg_password.equals(""));

      try
      {
        Socket socket = new Socket(metaServerHost, metaServerPort);

        PrintStream out = new PrintStream(socket.getOutputStream());
        BufferedReader in = new BufferedReader(new InputStreamReader(
            socket.getInputStream()));

        String username = (arg_username.equals("") ? usernameField.getText() : arg_username);
        String password = (arg_password.equals("") ? passwordField.getText() : arg_password);
        
        System.out.println("Sending: " + username + " " + password + "##");

        // first AUTHENTICATE
        String line = in.readLine();
        assert_receive(line, "AUTHENTICATE");

        out.println(username);
        String pw_hashed = Helpers.MD5(password);
        out.println(pw_hashed);

        line = in.readLine();
        System.out.println(line);

        if (!line.equals("LOGINSUCC"))
        {
          statusmsg.setText("Login failed.");
          passwordField.setText("");
          usernameField.setText("");
          usernameField.requestFocus();

          return;
        }

        if (!nowindow)
        {
          statusmsg.setText("Logging in..");
          login.requestFocus();
          usernameField.setRequestFocusEnabled(false);
          passwordField.setRequestFocusEnabled(false);
          login.setRequestFocusEnabled(false);
          login.setEnabled(false);
        }

        main.set(this, socket, in, out, username);
        main.setLoggedIn(true);
        main.wakeup();
      }
      catch(Exception e)
      {
        e.printStackTrace();

        if (!nowindow)
        {
          statusmsg.setText("Login failed: " + e.toString());        
          passwordField.setText("");
          usernameField.setText("");
          usernameField.requestFocus();
        }

      }
    }


    /**
    * @param args the command line arguments
    */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new LoginFrame().setVisible(true);
            }
        });
    }

  // Variables declaration - do not modify//GEN-BEGIN:variables
  private javax.swing.JPanel jPanel1;
  private javax.swing.JButton login;
  private javax.swing.JLabel password;
  private javax.swing.JPasswordField passwordField;
  private javax.swing.JLabel statusmsg;
  private javax.swing.JLabel title;
  private javax.swing.JLabel username;
  private javax.swing.JTextField usernameField;
  // End of variables declaration//GEN-END:variables

}
